<template>
	<view class="content">
		<icon type="info" size="26" class="info-button" :style="'top:' + statusBarHeight + 'px'" />
		<drag-button :isDock="true" :existTabBar="true" @btnClick="btnClick" @btnTouchstart="btnTouchstart"
			@btnTouchend="btnTouchend">
		</drag-button>
		<image class="logo" :src="src"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
			<progress :percent="pgImg" show-info stroke-width="3" />
		</view>
		<button type="primary" plain @click="upload">选择文件“后”上传</button>
		<button type="primary" plain @click="getWxacode">生成分享码</button>
		<button type="primary" plain @click="getWeather">获取天气</button>
		<button type="primary" plain @click="getUsers">cloud-database</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello',
				statusBarHeight: 25,
				pgImg: 0,
				src: '/static/logo.png'
			}
		},
		onLoad() {
			uni.getSystemInfo({
				success: (data) => {
					console.log(data)
					this.statusBarHeight = data.statusBarHeight
					if (data.osName === 'ios') {
						this.statusBarHeight = data.statusBarHeight + 44
					}
				}
			});
			let curPage = getCurrentPages();
			let route = curPage[curPage.length - 1].route; //获取当前页面的路由
			let params = curPage[curPage.length - 1].options; //获取当前页面参数，如果有则返回参数的对象，没有参数返回空对象{}
			let query = '';
			let keys = Object.keys(params); //获取对象的key 返回对象key的数组
			if (keys.length > 0) {
				query = keys.reduce((pre, cur) => {
					return pre + cur + '=' + params[cur] + '&';
				}, '?').slice(0, -1);
			}
			console.log(route + query)
		},
		methods: {
			saveAlbum() {
				uni.getSetting({ //获取用户的当前设置
					success: (res) => {
						// console.log("获取权限",res);
						if (res.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
							// 开始存盘逻辑;
							uni.showToast({
								title: "开始存盘逻辑",
								icon: "none",
								duration: 3000
							});
						} else {
							uni.authorize({ //如果没有授权，向用户发起请求
								scope: 'scope.writePhotosAlbum',
								success: () => {
									// 开始存盘逻辑;
									uni.showToast({
										title: "开始存盘逻辑",
										icon: "none",
										duration: 3000
									});
								},
								fail: () => {
									uni.showToast({
										title: "请打开保存相册权限，再点击保存相册分享",
										icon: "none",
										duration: 3000
									});
									setTimeout(() => {
										uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
											success: (res2) => {
												// console.log(res2.authSetting)
											}
										});
									}, 3000);
								}
							})
						}
					}
				})
			},
			async getWxacode() {
				uni.showLoading({
					title: '处理中...'
				})
				this.src = ''
				return await uniCloud.callFunction({
					name: 'getWxacode',
					data: {
						path: 'pages/cloudFunction/cloudFunction',
						width: 400,
						createTime: Date.now()
					}
				}).then((res) => {
					const arrayBuffer = new Uint8Array(res.result.data)
					// 将src绑定到图片即可
					this.src = `data:image/jpeg;base64,${uni.arrayBufferToBase64(arrayBuffer)}`
					uni.hideLoading()
				}).catch((err) => {
					uni.hideLoading()
					console.error(err)
				})
			},
			async getWeather() {
				uni.request({
					url: 'http://t.weather.itboy.net/api/weather/city/101200101', //仅为示例，并非真实接口地址。
					data: {
						text: 'uni.request'
					},
					header: {
						'custom-header': 'hello' //自定义请求头信息
					},
					success: (res) => {
						console.log(res.data);
						uni.showToast({
							title: res.data.cityInfo.city + "温度：" + res.data.data.wendu + "℃",
							icon: "none",
							duration: 3000
						});
					}
				});
			},
			async getUsers() {
				try {
					const db = uniCloud.database()
					let res = await db.collection('uni-id-users').field(
						"_id").get()
					if (res.result.code === 0 && res.result.data.length > 0) {
						uni.showToast({
							title: "共有" + res.result.data.length + "个用户",
							icon: "none",
							duration: 3000
						});
					} else {
						uni.showToast({
							title: "找不到任何用户",
							icon: "none",
							duration: 3000
						});
					}
				} catch (e) {
					console.log(e)
				}
			},
			btnClick() {

			},
			btnTouchstart() {

			},
			btnTouchend() {

			},
			upload() {
				let that = this
				new Promise((resolve, reject) => {
					that.pgImg = 0
					uni.chooseImage({
						count: 1,
						success: res => {
							const path = res.tempFilePaths[0]
							let ext
							// #ifdef H5
							ext = res.tempFiles[0].name.split('.').pop()
							const options = {
								filePath: path,
								cloudPath: Date.now() + '.' + ext
							}
							resolve(options)
							// #endif
							// #ifndef H5
							uni.getImageInfo({
								src: path,
								success(info) {
									const options = {
										filePath: path,
										cloudPath: Date.now() + '.' + info.type
											.toLowerCase()
									}
									resolve(options)
								},
								fail(err) {
									reject(new Error(err.errMsg || '未能获取图片类型'))
								}
							})
							// #endif
						},
						fail: () => {
							reject(new Error('Fail_Cancel'))
						}
					})
				}).then((options) => {
					uni.showLoading({
						title: '文件上传中...'
					})
					return uniCloud.uploadFile({
						...options,
						onUploadProgress(e) {
							console.log(e)
							that.pgImg = parseInt(e.loaded / e.total) * 100
						}
					})
				}).then(res => {
					uni.hideLoading()
					console.log(res);
					uni.showModal({
						content: '图片上传成功，fileId为：' + res.fileID,
						showCancel: false
					})
					this.src = res.fileID
				}).catch((err) => {
					uni.hideLoading()
					console.log(err);
					if (err.message !== 'Fail_Cancel') {
						uni.showModal({
							content: `图片上传失败，错误信息为：${err.message}`,
							showCancel: false
						})
					}
				})
			}
		},
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>